import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useSettingsStore = defineStore('settings', () => {
  // 全局设置
  const settings = ref({
    defaultDownloadPath: 'D:\\download', // 默认下载位置
    defaultConcurrentThreads: 8, // 默认并发线程数
    defaultRetryCount: 3, // 默认重试次数
    autoStartDownload: true, // 创建任务后自动开始下载
    showDownloadSpeed: true, // 显示下载速度
    autoCleanupCompleted: false, // 自动清理已完成任务
    cleanupAfterDays: 7, // 清理天数
    maxConcurrentTasks: 3, // 最大并发任务数
    enableNotifications: true, // 启用通知
    language: 'zh-CN' // 语言设置
  })

  // 从localStorage加载设置
  const loadSettings = () => {
    try {
      const savedSettings = localStorage.getItem('m3u8-downloader-settings')
      if (savedSettings) {
        const parsed = JSON.parse(savedSettings)
        settings.value = { ...settings.value, ...parsed }
      }
    } catch (error) {
      console.error('Failed to load settings:', error)
    }
  }

  // 保存设置到localStorage
  const saveSettings = () => {
    try {
      localStorage.setItem('m3u8-downloader-settings', JSON.stringify(settings.value))
    } catch (error) {
      console.error('Failed to save settings:', error)
    }
  }

  // 更新设置
  const updateSettings = (newSettings) => {
    settings.value = { ...settings.value, ...newSettings }
    saveSettings()
  }

  // 重置设置
  const resetSettings = () => {
    settings.value = {
      defaultDownloadPath: 'D:\\download',
      defaultConcurrentThreads: 8,
      defaultRetryCount: 3,
      autoStartDownload: true,
      showDownloadSpeed: true,
      autoCleanupCompleted: false,
      cleanupAfterDays: 7,
      maxConcurrentTasks: 3,
      enableNotifications: true,
      language: 'zh-CN'
    }
    saveSettings()
  }

  // 获取默认下载路径
  const getDefaultDownloadPath = computed(() => settings.value.defaultDownloadPath)

  // 获取默认并发线程数
  const getDefaultConcurrentThreads = computed(() => settings.value.defaultConcurrentThreads)

  // 获取默认重试次数
  const getDefaultRetryCount = computed(() => settings.value.defaultRetryCount)

  // 是否显示下载速度
  const shouldShowDownloadSpeed = computed(() => settings.value.showDownloadSpeed)

  // 初始化设置
  const initialize = () => {
    loadSettings()
  }

  return {
    settings,
    loadSettings,
    saveSettings,
    updateSettings,
    resetSettings,
    getDefaultDownloadPath,
    getDefaultConcurrentThreads,
    getDefaultRetryCount,
    shouldShowDownloadSpeed,
    initialize
  }
}) 